﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GheSofa.Models;
using System.Web.Security;

namespace GheSofa.Controllers
{
    public class NguoiDungController : Controller
    {
        GheSofaEntities db = new GheSofaEntities();

        [HttpGet]
        public ActionResult DangNhap()
        {
            return View();
        }

        public bool kiemtradangnhap(TaiKhoan tk)
        {
            var danhsach = (from ds in db.TaiKhoans select ds).ToList();
            foreach (TaiKhoan item in danhsach)
            {
                if (item.TenTK.Equals(tk.TenTK) && item.MatKhau.Equals(tk.MatKhau))
                    return true;
            }
            return false;
        }

        [HttpPost]
        public ActionResult DangNhap(dangnhap model, string returnUrl)
        {
            try
            {
                TaiKhoan nd = new TaiKhoan();
                nd.TenTK = model.username;
                nd.MatKhau = model.password;
                bool _remember = model.remember;
                bool userValid = kiemtradangnhap(nd);
                if (userValid)
                {
                    Session["user"] = nd.TenTK;
                    FormsAuthentication.SetAuthCookie(nd.TenTK, _remember);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("TrangChu", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Sai tên hoặc mật khẩu đăng nhập");
                    return View();
                }
            }
            catch
            {
                return View();
            }
        }

        public ActionResult SuaThongTin()
        {
            if (Session["user"] == null)
            {
                return View();
            }
            else
            {
                string username = Session["user"].ToString();
                var kh = (from k in db.KhachHangs select k).ToList();
                KhachHang tk = new KhachHang();
                foreach (KhachHang item in kh)
                    if (item.TenTK.Equals(username))
                    {
                        tk = item;
                        break;
                    }
                suathongtin _sua = new suathongtin();
                _sua.username = tk.TenTK;
                _sua.hoten = tk.TenKH;
                _sua.sdt = tk.SDT;
                _sua.email = tk.Email;
                _sua.password = null;
                _sua.passwordcu = null;
                _sua.xacnhanmatkhau = null;
                return View(_sua);
            }
        }

        [HttpPost]
        public ActionResult SuaThongTin(suathongtin nd_sua)
        {
            TaiKhoan _nd = new TaiKhoan();
            _nd.TenTK = nd_sua.username;
            _nd.MatKhau = nd_sua.passwordcu;
            if (Session["user"].Equals(_nd.TenTK))
            {
                if (nd_sua.password == null || !nd_sua.password.Equals(nd_sua.xacnhanmatkhau))
                {
                    ViewBag.saithongtin = "";
                    return View(nd_sua);
                }
                else
                {
                    bool userValid = kiemtradangnhap(_nd);
                    if (userValid)
                    {
                        var dsnd = (from ds in db.KhachHangs select ds).ToList();
                        var dstk = (from tk in db.TaiKhoans select tk).ToList();
                        foreach (KhachHang item in dsnd)
                            if (item.TenTK.Equals(nd_sua.username))
                            {                                
                                item.SDT = nd_sua.sdt;
                                item.Email = nd_sua.email;
                                break;
                            }
                            foreach (TaiKhoan u in dstk)
                            if (u.TenTK == nd_sua.username)
                            {
                                u.MatKhau = nd_sua.password;
                                break;
                            }
                        db.SaveChanges();
                        return RedirectToAction("TrangChu", "Home");
                    }
                    else
                    {
                        ViewBag.saithongtin = "Sai mật khẩu cũ";
                        return View(nd_sua);
                    }

                }
            }
            else
            {
                return RedirectToAction("TrangChu", "Home");
            }
        }

        public ActionResult DangXuat()
        {
            Session["user"] = null;
            FormsAuthentication.SignOut();
            return RedirectToAction("TrangChu", "Home");
        }

        [HttpGet]
        public ActionResult DangKy()
        {
            ngaythangnam();
            return View();
        }

        [HttpPost]
        public ActionResult DangKy(dangky model, FormCollection form)
        {
            var khachhang = (from k in db.KhachHangs select k).ToList(); 
            var taikhoan = (from t in db.TaiKhoans select t).ToList();
            int gt = int.Parse(form["gioitinh"].ToString());
            int ngay = int.Parse(form["ngay"]);
            int thang = int.Parse(form["thang"]);
            int nam = int.Parse(form["nam"]);
            if (kiemtrangaysinh(ngay, thang, nam))
            {
                DateTime ns = new DateTime(nam, thang, ngay);
                try
                {
                    KhachHang kh = new KhachHang();
                    TaiKhoan tk = new TaiKhoan();
                    kh.MaKH = SinhMa();
                    kh.TenTK = model.username;                   
                    kh.TenKH = model.hoten;
                    kh.NgaySinh = ns;
                    kh.GioiTinh = gt;
                    kh.SDT = model.sdt;
                    kh.DiaChi = model.diachi;
                    kh.Email = model.email;

                    tk.TenTK = model.username;
                    tk.MatKhau = model.password;
                    tk.PhanQuyen = 2;
                    if (kiemtranguoidung(kh))
                    {
                        db.TaiKhoans.Add(tk);
                        db.SaveChanges();
                        db.KhachHangs.Add(kh);
                        db.SaveChanges();
                        ViewBag.thanhcong = "Đăng ký thành công!";
                    }
                    else
                    {
                        ngaythangnam();
                        ViewBag.thanhcong = null;
                    }
                    ViewBag.thatbai = "Tên đăng nhập đã tồn tại!";
                    ngaythangnam();
                    return View();
                }
                catch
                {
                    ngaythangnam();
                    return View();
                }
            }
            else
            {
                ngaythangnam();
                ViewBag.loi = "Ngày sinh không hợp lệ!";
            }
            ngaythangnam();
            return View();
        }

        public string SinhMa()
        {
            var kh = (from k in db.KhachHangs select k).ToList();
            KhachHang end = new KhachHang();
            foreach (KhachHang item in kh)
            {
                end = item;
            }
            string ma = end.MaKH;
            string so = ma.Substring(2, 3);
            int num = int.Parse(so) + 1;
            if (num < 10)
            {
                return "KH0" + num;
            }
            else
            {
                return "KH" + num;
            }
        }

        public bool kiemtranguoidung(KhachHang kh)
        {
            var taikhoan = (from t in db.TaiKhoans select t).ToList();
            foreach (TaiKhoan item in taikhoan)
            {
                if (item.TenTK.Equals(kh.TenTK))
                    return false;
            }
            var khachHang = (from k in db.KhachHangs select k).ToList();
            foreach (KhachHang item in khachHang)
            {
                if (item.TenTK.Equals(kh.TenTK))
                    return false;
            }
            return true;
        }

        bool kiemtranamnhuan(int nam)
        {
            if (nam % 4 == 0 && nam % 100 != 0)
                return true;
            return false;
        }

        bool kiemtrangaysinh(int ngay, int thang, int nam)
        {
            int ngaynhuan = 0;
            if (thang == 2)
            {
                if (kiemtranamnhuan(nam))
                    ngaynhuan = 29;
                else
                    ngaynhuan = 28;
                if (ngay > ngaynhuan)
                {
                    return false;
                }
            }
            else
                if (thang == 4 || thang == 6 || thang == 9 || thang == 11)
                    if (ngay > 30)
                        return false;
            return true;
        }

        public void ngaythangnam()
        {
            int namtu = DateTime.Now.Year - 65;
            int namden = DateTime.Now.Year - 16;
            List<SelectListItem> ngayList = new List<SelectListItem>();
            List<SelectListItem> thangList = new List<SelectListItem>();
            List<SelectListItem> namList = new List<SelectListItem>();
            for (int i = 1; i <= 31; i++)
            {
                string j = i.ToString();
                ngayList.Add(new SelectListItem { Text = j, Value = j });
            }
            for (int i = 1; i <= 12; i++)
            {
                string j = i.ToString();
                thangList.Add(new SelectListItem { Text = j, Value = j });
            }
            for (int i = namtu; i <= namden; i++)
            {
                string j = i.ToString();
                namList.Add(new SelectListItem { Text = j, Value = j });
            }
            ViewBag.ngay = ngayList;
            ViewBag.thang = thangList;
            ViewBag.nam = namList;
        }
    }
}
